<template>
  <BasePage>
    <MyTable
      ref="$table"
      :columns="columns"
      :query-schemas="querySchemas"
      :get-data="roleApi.list"
      :index="true"
    >
      <template #handle>
        <AddButton v-auth="`role_manage_add`" @click="handleAdd">添加角色</AddButton>
      </template>
    </MyTable>
    <MyForm ref="$form" :model-form="model" @submit="handleSubmit">
      <n-form-item
        label="角色名称"
        path="name"
        :rule="{ required: true, message: '请输入角色名称' }"
      >
        <n-input
          v-model:value="model.name"
          maxlength="20"
          clearable
          show-count
          :disabled="model.isSet"
        />
      </n-form-item>
      <n-form-item label="备注" path="remark">
        <n-input
          v-model:value="model.remark"
          type="textarea"
          maxlength="100"
          clearable
          show-count
          :autosize="{
            minRows: 3,
          }"
          :disabled="model.isSet"
        />
      </n-form-item>
      <n-form-item label="选择权限" path="authorityIdList">
        <n-tree
          :checked-keys="model.authorityIdList"
          key-field="id"
          checkable
          block-line
          :selectable="false"
          :data="menuTree"
          @update:checked-keys="updateCheckedKeys"
        />
      </n-form-item>
    </MyForm>
  </BasePage>
</template>
<script setup lang="jsx">
defineOptions({ name: 'RoleMange' })
import * as roleApi from '@/api/role'
import * as menuAuthApi from '@/api/menuAuth'
import { useCrud } from '@/hooks/useCrud'
const querySchemas = []
const columns = [
  {
    title: '角色名称',
    key: 'name',
  },
  {
    title: '备注',
    key: 'remark',
  },
  {
    title: '创建时间',
    key: 'createTime',
  },
  {
    title: '操作',
    key: 'actions',
    width: 180,
    align: 'left',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return (
        <n-flex>
          <ActionButton onClick={() => setMenuAuth(row)}>配置权限</ActionButton>
          <ActionButton onClick={() => handleEdit(row)}>修改</ActionButton>
          <ActionButton onClick={() => handleDel(row)}>删除</ActionButton>
        </n-flex>
      )
    },
  },
]
function setMenuAuth(row) {
  handleEdit(row, {
    title: '配置权限',
    onShow: () => {
      model.value.isSet = true
    },
  })
}
const { type, model, $form, $table, handleAdd, handleEdit, handleDel, handleSubmit } = useCrud({
  name: '角色',
  initForm: {
    id: null,
    name: null,
    remark: null,
    authorityIdList: [],
    isSet: false,
  },
  apis: {
    add: roleApi.add,
    edit: (params) => {
      return Promise.all([() => roleApi.edit(params), roleApi.setRoleMenuAuth(params)])
    },
    del: ({ id }) => roleApi.del(id),
    view: async ({ id }) => {
      const [info, authorityIdList] = await Promise.all([
        roleApi.info(id).then((res) => res.data),
        roleApi.getRoleMenuAuth(id).then((res) => res.data),
      ])
      return { ...info, authorityIdList }
    },
  },
})

const menuTree = ref([])
async function getMenuTree() {
  const { data } = await menuAuthApi.tree()
  menuTree.value = data
}
function getIds(array, ids = []) {
  array.forEach((item) => {
    if (item.id) {
      ids.push(item.id)
    }
    if (item.children) {
      ids = getIds(item.children, ids)
    }
  })
  return ids
}

function updateCheckedKeys(keys, _, { action, node }) {
  const ids = getIds([node])
  if (action === 'check') {
    keys = [...new Set(keys.concat(ids))]
  } else if (action === 'uncheck') {
    keys = keys.filter((id) => !ids.includes(id))
  }
  model.value.authorityIdList = keys
}
onBeforeMount(() => {
  getMenuTree()
})
</script>
<style lang="scss" scoped></style>
